package com.soulapp.hook.hooker

import android.widget.Toast
import com.highcapable.kavaref.KavaRef.Companion.resolve
import com.highcapable.kavaref.condition.type.Modifiers
import com.highcapable.yukihookapi.hook.core.YukiMemberHookCreator
import com.highcapable.yukihookapi.hook.log.YLog
import com.soulapp.data.ConfigData

// 禁止自动更新
object LimitUpdateHook : BaseHooker() {

    private const val TAG = "LimitUpdateHook"
    private var hook: YukiMemberHookCreator.MemberHookCreator.Result? = null

    override fun getKey() = ConfigData.autoUpdate

    override fun onHook() {
        startHook()
    }

    override fun startHook() {
        YLog.debug("startHook $TAG $hookEnabled")
        if (!hookEnabled) return

        // 屏蔽全局弹窗
        val className = "nh.b"
        hook = className.toClass()
            .resolve()
            .optional()
            .method {
                modifiers(Modifiers.PUBLIC)
                name("showGlobalWindow")
                parameterCount(2)
                returnType = Boolean::class.javaPrimitiveType
            }.first()
            .hook {
                // replaceToTrue()
                replaceAny {
                    val showToast = ConfigData.getBoolean(ConfigData.showToast)
                    if (showToast) {
                        Toast.makeText(appContext, "禁止更新弹窗", Toast.LENGTH_SHORT).show()
                    }
                    true
                }
            }
    }

    override fun stopHook() {
        if (!hookEnabled) return

        hook?.let {
            it.remove {
                YLog.debug("stopHook $TAG 成功")
            }
        } ?: YLog.debug("stopHook $TAG 失败")

        hookEnabled = false
    }

}